using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinformApp = System.Windows.Forms.Application;

namespace Comteck.Winforms.Utils {
  /// <summary>
  /// Log4Net
  /// </summary>
  public class Log4NetHelper {
    /// <summary>
    /// lo4net默认的文件名
    /// </summary>
    public const string DEFAULT_FILENAME = "log4net.config";

    /// <summary>
    /// 加载配置文件
    /// </summary>
    /// <param name="absoluteFileName"></param>
    public static void Load(string absoluteFileName = null) {
      absoluteFileName = absoluteFileName ?? $"{WinformApp.StartupPath}\\{DEFAULT_FILENAME}";

      if (File.Exists(absoluteFileName)) {
        var file = new System.IO.FileInfo(absoluteFileName);
        log4net.Config.XmlConfigurator.ConfigureAndWatch(file);
      } else {
        System.Diagnostics.EventLog.WriteEntry(Assembly.GetEntryAssembly().GetName().Name, $"{absoluteFileName} 没有找到", System.Diagnostics.EventLogEntryType.Warning);
      }
    }

    /// <summary>
    /// 删除log4net的历史文件
    /// </summary>
    /// <param name="logDic">log4net文件夹的相对路径</param>
    /// <param name="holdDays">保留天数</param>
    public static void DeleteFiles(string logDic = "logs", int holdDays = 7) {
      // 文件夹名称
      var folderName = $"{WinformApp.StartupPath}\\{logDic}";

      // 根节点
      var rootDic = new DirectoryInfo(folderName);

      // 不存在
      if (rootDic.Exists == false) {
        return;
      }

      // 处理文件或者文件夹
      HandleFileSystems(rootDic.GetFiles(), rootDic.GetDirectories(), holdDays);
    }

    /// <summary>
    /// 处理文件或者文件夹
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="holdDays"></param>
    private static void HandleFileSystems(FileInfo[] files, DirectoryInfo[] directories, int holdDays) {
      // 先处理文件
      files?.Each((file) => HandleFile(file, holdDays));

      // 再处理文件夹
      foreach (var directory in directories) {
        // 递归处理
        HandleFileSystems(directory.GetFiles(), directory.GetDirectories(), holdDays);

        // 判断该文件夹里是否有文件，如果没有，则直接删除文件夹
        if (directory.GetFileSystemInfos().IsNullOrEmpty()) {
          directory.Delete();
        }
      }
    }

    /// <summary>
    /// 处理文件
    /// </summary>
    /// <param name="file"></param>
    /// <param name="holdDays"></param>
    private static void HandleFile(FileInfo file, int holdDays) {
      if (DateTime.Now.Date.Subtract(file.CreationTime.Date).TotalDays >= holdDays) {
        try {
          file.Delete();
        } catch {
        }
      }
    }

  }
}
